package org.webguitoolkit.project.runtime;

import java.util.Hashtable;


import org.webguitoolkit.project.model.impl.Issue;
import org.webguitoolkit.project.query.IQueryFactory;
import org.webguitoolkit.project.query.impl.QueryFactory;
import com.endress.infoserve.persistence.PersistenceContext;
import com.endress.infoserve.persistence.PersistenceManager;
import com.endress.infoserve.persistence.util.HibernateUtility;

public class ModelContext extends PersistenceContext{
	
	protected static final String USER = "user";

	protected PersistenceManager persistenceManager;

	protected static ThreadLocal<ModelContext> pc = new ThreadLocal<ModelContext>();

	protected Hashtable<String, Object> data = new Hashtable<String, Object>();
	
	public ModelContext() {
		super();
	}

	public static ModelContext getInstance() {
		return pc.get();
	}

	public void initialize(String hibernateConfig, String currentUser) {
		initialize( hibernateConfig );

		// find user in user data base
//		Collection<IUser> users = getQueryFactory().newUserQuery(currentUser).execute();
//		if (!users.isEmpty())
//			setUser(users.iterator().next());
		getPersistenceManager().setUserid(currentUser);
	}

	public void initialize(String hibernateConfig) {
		pc.set(this);

		HibernateUtility hu = new HibernateUtility(getAnnotatedClasses(), hibernateConfig);
		PersistenceManager pm = new PersistenceManager(hu);
		initialize(pm);
	}

	public void initialize(PersistenceManager pm) {
		PersistenceContext.setPersistenceManager(pm);
		persistenceManager = pm;
	}

	@SuppressWarnings( value="unchecked" )
	public static Class[] getAnnotatedClasses() {
		Class[] annotated = new Class[] { Issue.class };
		return annotated;
	}

//	User handling
//	public IUser getUser() {
//		return (IUser) data.get(USER);
//	}
//
//	public void setUser(IUser user) {
//		data.put(USER, user);
//	}

	public static IQueryFactory getQueryFactory() {
		return new QueryFactory( getPersistenceManager() );
	}

}
